//
//  JXRegisterController.m
//  JiaoX
//
//  Created by jiaoxiu－005 on 15/1/12.
//  Copyright (c) 2015年 北京娇羞科技有限公司. All rights reserved.
//

#import "JXRegisterController.h"
#import "JXNavigationController.h"
#import "JXBaseRequest.h"
#import "SelfDataTool.h"
#import "LoginRes.h"
#import "UserDefaultsHelper.h"
#import "JXMineController.h"
#import "ConfigConstants.h"
#import "JXLoginRegistCheckController.h"
#import "AppDelegate.h"
#import "JXTabBarController.h"
#import "TalkingDataAppCpa.h"
#define  Edit_Width JXScreenW-JXPublicInset*2
#define  Edit_Height 46.5


@interface JXRegisterController ()<UIScrollViewDelegate>

@property(nonatomic,strong)  UIScrollView *scrollView;
@property(nonatomic,strong)  UITextField *phoneCode;
@property(nonatomic,strong)  UITextField *userName;
@property(nonatomic,strong)  UITextField *password;
@property(nonatomic,strong)  UIButton *enterRegist;

@end

@implementation JXRegisterController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"重设密码";
    [self.view setBackgroundColor:[UIColor whiteColor]];
    //添加阻尼效果
    UIScrollView *scrollView = [[UIScrollView alloc]init];
    scrollView.frame = CGRectMake(0, 0, JXScreenW, self.view.height);
    [scrollView setContentSize:CGSizeMake(JXScreenW, self.view.height)];
    scrollView.showsVerticalScrollIndicator = FALSE;
    scrollView.showsHorizontalScrollIndicator = FALSE;
    scrollView.delegate = self;
    self.scrollView = scrollView;
    [self.view addSubview:scrollView];
    //初始化手机号输入框
    [self initPhoneCodeTextField];
//    初始化用户名输入框
//    [self initUserNameTextField];
    //初始化密码输入框
    [self initPasswordTextField];
    //确认修改按钮
    [self initEnterModifyButton];
}

/**
 *  重写scrollview的滚动方法隐藏软件盘，结束输入,成为scrollview的代理才可以使用这个方法
 *
 *  @param scrollView
 */
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

/**
 *初始化手机号输入框
 */
-(void)initPhoneCodeTextField{
    UITextField *phoneCode = [[UITextField alloc]init];
    //frame
    CGFloat phoneCodeX = JXPublicInset;
    CGFloat phoneCodeY = 20;
    CGRect rect =  CGRectMake(phoneCodeX, phoneCodeY, Edit_Width, Edit_Height);
    [self initTextField:self.scrollView edit:phoneCode frame:rect placeholderText:@"手机号"];
    phoneCode.keyboardType = UIKeyboardTypePhonePad;
    self.phoneCode = phoneCode;
}

/**
 *初始化用户名输入框
 */
-(void)initUserNameTextField{
    UITextField *validateCode = [[UITextField alloc]init];
    //frame
    CGRect rect =  CGRectMake(JXPublicInset, CGRectGetMaxY(self.phoneCode.frame)+10,Edit_Width, Edit_Height);
    [self initTextField:self.scrollView edit:validateCode frame:rect placeholderText:@"用户名"];
    self.userName = validateCode;
}

/**
 *初始化密码输入框
 */
-(void)initPasswordTextField{
    UITextField *newPassword = [[UITextField alloc]init];
    //frame
    newPassword.secureTextEntry = YES;
    CGRect rect =  CGRectMake(JXPublicInset, CGRectGetMaxY(self.phoneCode.frame)+10,Edit_Width, Edit_Height);
    [self initTextField:self.scrollView edit:newPassword frame:rect placeholderText:@"密码"];
    self.password = newPassword;
}

/**
 *初始化确认修改按钮
 */
-(void)initEnterModifyButton{
    UIButton *enterModify =[[UIButton alloc]init];
    [enterModify.titleLabel setFont:[UIFont systemFontOfSize:[DimensUtils getScaleX:15]]];
    [enterModify setTitle:@"立即注册" forState:UIControlStateNormal];
    [enterModify setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [enterModify setContentMode:UIViewContentModeCenter];
    enterModify.frame = CGRectMake(JXPublicInset, CGRectGetMaxY(self.password.frame)+10, Edit_Width,  Edit_Height);
    [enterModify setBackgroundImage:[UIImage resizedImage:@"btn_login_bg"] forState:UIControlStateNormal];
    [enterModify addTarget:self action:@selector(regist) forControlEvents:UIControlEventTouchUpInside];
    self.enterRegist = enterModify;
    [self.scrollView addSubview:enterModify];
}

/**
 *  初始化输入框
 */
-(void)initTextField :(UIView *)container edit:(UITextField *)edit frame:(CGRect)frame placeholderText:(NSString *)placeholderText{
    //设置边框
    [edit.layer setBorderColor:JXColor(204, 204, 204).CGColor];
    [edit.layer setBorderWidth:0.7];
    [edit.layer setCornerRadius:5];
    
    edit.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    edit.attributedPlaceholder =[[NSAttributedString alloc] initWithString:placeholderText attributes:@{NSForegroundColorAttributeName: JXColor(204, 204, 204)}];
    edit.frame = frame;
    edit.clearButtonMode = UITextFieldViewModeAlways;
    [self textFieldAddleftView:edit];
    [container addSubview:edit];
}

/**
 *  输入框左边增加左边距
 *
 *  @param edit
 */
-(void)textFieldAddleftView:(UITextField *)edit{
    //添加左边距
    CGRect frame = [edit frame];
    frame.size.width = 7.0f;
    UIView *leftview = [[UIView alloc] initWithFrame:frame];
    edit.leftViewMode = UITextFieldViewModeAlways;
    edit.leftView = leftview;
}

/**
 *  确认修改
 */
-(void) regist{
    NSString *phoneCode = self.phoneCode.text;
    NSString *userName = self.userName.text;
    NSString *password = self.password.text;
    if([Utils isBlankString:phoneCode]){
        [DialogUtils showTipsWithView:self.view String:@"手机号不能为空"];
        return;
    }
//    if([Utils isBlankString:userName]){
//        [DialogUtils showTipsWithView:self.view String:@"用户名不能为空"];
//        return;
//    }
    if([Utils isBlankString:password]){
        [DialogUtils showTipsWithView:self.view String:@"密码不能为空"];
        return;
    }
    if ([Utils getLengthWithStr:userName]>16) {
        [DialogUtils showTipsWithView:self.navigationController.view String:@"用户名不能超过8个汉字"];
        return;
    }
    MBProgressHUD *loding = [DialogUtils showLoadingWithView:self.view];
    JXBaseRequest *request = [[JXBaseRequest alloc]init];
    NSDictionary *dic = [request keyValues];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:dic];
    [params setObject:phoneCode forKey:@"phoneCode"];
//    [params setObject:userName forKey:@"username"];
    [params setObject:password forKey:@"password"];
    [SelfDataTool registWithParam:params success:^(JXBaseResponse *result) {
        [loding hide:YES];
        if([Utils isBlankString:[result data]]){//注册密码成功
            [DialogUtils showTipsWithView:self.view String:@"注册成功"];
            JXLog(@"注册成功");
            [self login:phoneCode password:password];
        }else{//注册失败
            [DialogUtils showTipsWithView:self.view String:[result data]];
            JXLog(@"注册失败:%@",[result data]);
        }
    } failure:^(NSError *error) {
        [loding hide:YES];
        [DialogUtils showTipsWithView:self.view String:@"注册失败"];
        JXLog(@"failure注册失败:%@",error);
    }];
}
/**
 *  执行登录
 */
-(void) login:(NSString *)username password:(NSString *)password{
    JXBaseRequest *request = [[JXBaseRequest alloc]init];
    NSDictionary *dic = [request keyValues];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:dic];
    [params setObject:username forKey:@"username"];
    [params setObject:password forKey:@"password"];
    MBProgressHUD *loding = [DialogUtils showLoadingWithView:self.view];
    [SelfDataTool loginDataInfoWithParam:params success:^(LoginRes *result) {
        [loding hide:YES];
        if([Utils isBlankString:[result data]]){//登录成功，保存token和secret
            [DialogUtils showTipsWithView:self.view String:@"登录成功"];
            // TODO 清除隐私保护密码
            [self resolveLoginParams:result];
        }else{//登录失败
            [DialogUtils showTipsWithView:self.view String:@"登录失败"];
            JXLog(@"登录失败:%@",[result data]);
        }
    } failure:^(NSError *error) {
        [loding hide:YES];
        [DialogUtils showTipsWithView:self.view String:@"登录失败"];
        JXLog(@"failure登录失败:%@",error);
    }];
}
/**
 *  处理登录成功的参数
 *
 *  @param result
 */
-(void)resolveLoginParams:(LoginRes *)result{
    NSString *token =  result.token;
    NSString *secret = result.screatKey;
    JXLog(@"screatKey : %@-----------token : %@",secret,token);
    [self saveBasePrams:token :secret];
    //TODO 1.提交本地购物车的数据
    //2.获取用户信息
    [self getUserInfo];
}

/**
 *  获取用户信息
 */
-(void) getUserInfo{
    [SelfDataTool getUserInfoWithUserId:@"" success:^(UserInfo *result) {
        if([Utils isBlankString:[result data]]){//获取用户信息成功
            //注册之后的登录成功之后调用talkingdata的注册
            [TalkingDataAppCpa onRegister:result.userId];
            //1.保存用户信息
            [Utils saveUserInfo:result];
            //2.判断是直接关闭当前页面，还是跳转到MainTabAct(隐私)
            AppDelegate *myDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
            if (myDelegate.isClearPrivacyPwd) {
                myDelegate.isClearPrivacyPwd = NO;
                //直接前往tabcontroller
                UIWindow *window = [UIApplication sharedApplication].keyWindow;
                window.rootViewController = [[JXTabBarController alloc]init];
                [window makeKeyAndVisible];
            }else{
                [self back];
            }
        }
    } failure:^(NSError *error) {//获取用户信息失败
        JXLog(@"获取用户信息失败:%@",error);
    }];
}

/**
 *  保存token ,secret
 *
 *  @param token
 *  @param secret
 */
-(void)saveBasePrams:(NSString *)token :(NSString *)secret{
    if(![Utils isBlankString:token]){
        [UserDefaultsHelper setObject:token forKey:KEY_APPTOKEN];
    }
    if(![Utils isBlankString:secret]){
        [UserDefaultsHelper setObject:secret forKey:KEY_SERVER_SECRET_KEY];
    }
}
/**
 *  返回按钮
 */
-(void)back{
    UIViewController *c = [self.view.superview viewController];
    [c dismissViewControllerAnimated:NO completion:^{
    }];
}

@end
